<template>
  <div>
    <h1 class="page-title">
      <font-awesome-icon icon="file-alt" />
      需求优化
    </h1>

    <Tabs
      :tabs="tabs"
      default-tab="req-input"
      @tab-change="handleTabChange"
    >
      <template #req-input>
        <div class="content-box">
          <textarea
            v-model="requirementsInput"
            class="input-area"
            placeholder="请输入您的需求文本..."
          ></textarea>
          <button
            class="btn btn-primary"
            @click="handleOptimize"
            :disabled="loading.requirements"
          >
            <span v-if="loading.requirements" class="loading"></span>
            <font-awesome-icon v-else icon="magic" />
            {{ loading.requirements ? '正在优化...' : '优化需求' }}
          </button>
        </div>
      </template>

      <template #req-upload>
        <div class="content-box">
          <FileUploader
            @file-selected="handleFileSelected"
            upload-text="拖拽文件到此处或点击上传"
            upload-subtext="支持Word、PDF和图片文件"
          />
          <button
            class="btn btn-primary"
            @click="handleOptimizeUpload"
            :disabled="loading.requirements || !uploadedFile"
            style="margin-top: 15px;"
          >
            <span v-if="loading.requirements" class="loading"></span>
            <font-awesome-icon v-else icon="magic" />
            {{ loading.requirements ? '正在解析并优化...' : '解析并优化需求' }}
          </button>
        </div>
      </template>
    </Tabs>

    <div class="content-box">
      <h2 class="result-title">优化后的需求</h2>
      <div class="result-content">
        <div v-if="loading.requirements" class="result-loading">
          <div v-for="i in 5" :key="i" class="result-loading-line"></div>
        </div>
        <div v-else-if="optimizedRequirements" v-html="formatMarkdown(optimizedRequirements.optimized)"></div>
        <p v-else>优化后的需求将显示在这里...</p>
      </div>
      <div class="btn-group">
        <button
          class="btn btn-outline"
          @click="handleCopy"
          :disabled="!optimizedRequirements"
        >
          <font-awesome-icon icon="copy" />
          复制到剪贴板
        </button>
        <button
          class="btn btn-outline"
          @click="handleExport"
          :disabled="!optimizedRequirements"
        >
          <font-awesome-icon icon="download" />
          导出为Markdown
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import Tabs from '@/components/Tabs.vue';
import FileUploader from '@/components/FileUploader.vue';
import { marked } from 'marked'; // 修改导入方式

export default {
  name: 'RequirementsPage',
  components: {
    Tabs,
    FileUploader
  },
  data() {
    return {
      tabs: [
        { id: 'req-input', label: '需求输入' },
        { id: 'req-upload', label: '需求上传' }
      ],
      requirementsInput: '用户登录功能：\n1. 用户可以通过用户名和密码登录系统\n2. 登录失败时显示错误信息',
      uploadedFile: null,
      activeTab: 'req-input'
    }
  },
  computed: {
    ...mapState(['optimizedRequirements', 'loading'])
  },
  methods: {
    ...mapActions(['optimizeRequirements', 'optimizeRequirementsFromFile', 'showNotification']),

    handleTabChange(tabId) {
      this.activeTab = tabId;
    },

    handleOptimize() {
      if (!this.requirementsInput.trim()) {
        this.showNotification({
          message: '请输入需求内容',
          type: 'error'
        });
        return;
      }

      this.optimizeRequirements({
        content: this.requirementsInput,
        title: '需求优化'
      });
    },

    handleFileSelected(file) {
      this.uploadedFile = file;
    },

    handleOptimizeUpload() {
      if (!this.uploadedFile) {
        this.showNotification({
          message: '请先上传需求文件',
          type: 'error'
        });
        return;
      }

      this.optimizeRequirementsFromFile({
        file: this.uploadedFile,
        title: this.uploadedFile.name
      });
    },

    handleCopy() {
      if (!this.optimizedRequirements) {
        this.showNotification({
          message: '没有可复制的内容',
          type: 'error'
        });
        return;
      }

      navigator.clipboard.writeText(this.optimizedRequirements.optimized)
        .then(() => {
          this.showNotification({
            message: '已复制到剪贴板',
            type: 'success'
          });
        })
        .catch(() => {
          this.showNotification({
            message: '复制失败，请手动复制',
            type: 'error'
          });
        });
    },

    handleExport() {
      if (!this.optimizedRequirements) {
        this.showNotification({
          message: '没有可导出的内容',
          type: 'error'
        });
        return;
      }

      // 创建Markdown内容
      const markdownContent = `# 优化后的需求\n\n${this.optimizedRequirements.optimized}`;

      // 创建Blob和下载
      const blob = new Blob([markdownContent], { type: 'text/markdown' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '优化后的需求.md';
      document.body.appendChild(a);
      a.click();

      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 0);

      this.showNotification({
        message: '需求已导出为Markdown文件',
        type: 'success'
      });
    },

    formatMarkdown(text) {
      if (!text) return '';
      try {
        return marked.parse(text); // 修改调用方式
      } catch (error) {
        console.error('Markdown解析错误:', error);
        this.showNotification({
          message: 'Markdown解析错误，请检查内容',
          type: 'error'
        });
        return text;
      }
    }
  }
}
</script>

<style scoped>
.input-area {
  width: 100%;
  min-height: 200px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  margin-bottom: 15px;
  font-family: inherit;
}

.result-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #111827;
}

.result-content {
  background-color: #f9fafb;
  border-radius: 6px;
  padding: 15px;
  min-height: 150px;
  margin-bottom: 15px;
  color: #4b5563;
}

.result-content :deep(h2) {
  font-size: 1.5em;
  margin-top: 0;
  margin-bottom: 0.5em;
  font-weight: 600;
  color: #111827;
}

.result-content :deep(h3) {
  font-size: 1.25em;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: 600;
  color: #111827;
}

.result-content :deep(ul), .result-content :deep(ol) {
  padding-left: 2em;
  margin-bottom: 1em;
}

.result-content :deep(li) {
  margin-bottom: 0.25em;
}

.result-content :deep(strong) {
  font-weight: 600;
  color: #111827;
}

.result-content :deep(p) {
  margin-bottom: 1em;
}

/* 加载状态样式 */
.result-loading {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-loading-line {
  height: 16px;
  background-color: #e5e7eb;
  border-radius: 4px;
  animation: pulse 1.5s infinite;
}

.result-loading-line:nth-child(1) {
  width: 80%;
}

.result-loading-line:nth-child(2) {
  width: 90%;
}

.result-loading-line:nth-child(3) {
  width: 70%;
}

.result-loading-line:nth-child(4) {
  width: 85%;
}

.result-loading-line:nth-child(5) {
  width: 75%;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}
</style>